package com.qqt.util;

import java.io.IOException;
import java.nio.charset.Charset;
import java.text.MessageFormat;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 
 * @author koywong
 *
 */
public class WechatConstants {

   private static final Logger  LOG             = LoggerFactory.getLogger(WechatConstants.class);
    
	public static final String WX_APPID=Parameters.getProperty("wx_appid","wxa5e6d934d0fd6073");
	
	public static final String WX_SECRET=Parameters.getProperty("wx_Secret","d200dcf5af1ba8d3c6b62d37504bdb46");
	
	public static final String WX_SERVICE_NO=Parameters.getProperty("wx_service_no","gh_c43e7555e6c8");
	

	/**
	 * 通过code换取网页授权access_token的URL
	 */
	public static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";
	
	/**
	 * 刷新access_token，由于access_token拥有较短的有效期，当access_token超时后，
	 * 可以使用refresh_token进行刷新，refresh_token拥有较长的有效期（7天、30天、60天、90天），
	 * 当refresh_token失效的后，需要用户重新授权。 
	 */
	public static final String REFRESH_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}";
	
	/**
	 * 获取用户信息(需scope为snsapi_userinfo)
	 */
	public static final String GET_USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN";
	
	
	
	public static String get_access_token(String code) {
        String url = MessageFormat.format(GET_ACCESS_TOKEN_URL, WX_APPID, WX_SECRET, code);
        HttpUriRequest request = new HttpGet(url);
        CloseableHttpClient client = HttpClientBuilder.create().build();
        try {
			CloseableHttpResponse response = client.execute(request);
			 int resultCode = response.getStatusLine().getStatusCode();
	            HttpEntity entity = response.getEntity();
	            //此流不是操作系统资源，不用关闭，ByteArrayOutputStream源码里close也是个空方法-0_0-
//	            OutputStream os = new ByteArrayOutputStream();
//	            entity.writeTo(os);
//	            String resultJson = os.toString();
	            String resultJson = EntityUtils.toString(entity, Charset.forName("UTF-8"));
	            //返回码200，请求成功；其他情况都为请求出现错误
	            if (HttpStatus.SC_OK == resultCode) {
	                LOG.debug("-----------------请求成功-----------------");
	                LOG.debug("响应结果:");
	                LOG.debug(resultJson);
	            } else {
	                LOG.warn("-----------------请求出现错误，错误码:{}-----------------", resultCode);
	            }
	            return resultJson;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		};
		return null;
    }
	
	/**
	 * 刷新access_token
	 * @param refresh_token
	 * @return
	 */
	public static String refreshAccessToken(String refresh_token) {
		String url = MessageFormat.format(REFRESH_TOKEN_URL, WX_APPID, refresh_token);
		//...
		
		return null;
	}
}
